import React, { useState, useRef } from "react";
import _ from 'lodash'
import { Form, Input, Select, Space, Button, DatePicker, Tabs } from "antd";
import { SearchOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { apiGetStoreInfoPage, apiStoreInfoRejected, apiStoreInfoApprove } from '@/request/store'
import { getDateTime3 } from '@/utils/getDate'
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import "../style/index.less";
import TheArea from '@/components/TheArea'
import { phoneReg } from '@/utils/regexp'
import _connect from '@/_connect'
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { TextArea } = Input;
const Item = Form.Item;

const SearchHeader = ({ getSearchValue }) => {
	const areaRef = useRef()
	const formRef = useRef()
	const [area, setArea] = useState({})
	const setAreaData = (value) => {
		value = {
			addressProvince: value.provinceName,
			addressCity: value.cityName,
			addressDistrict: value.areaName
		}
		setArea(value)
	}
	const onFinish = values => {
		if (!_.isEmpty(values.time)) {
			values.createdTimeStart = getDateTime3(values.time[0])
			values.createdTimeEnd = getDateTime3(values.time[1])
		}
		delete (values.time)
		values = {
			...values,
			...area
		}
		_.forIn(values, (v, k) => {
			if (!v) {
				delete (values[k])
			}
		})
		getSearchValue(values)
	}
	const reset = () => {
		formRef.current.setFieldsValue({
			storeName: '',
			contactsOrMobile: '',
			area: '',
			isProprietary: '',
			time: []
		})
		areaRef.current.init()
		getSearchValue({})
	}
	return <div className='search-box' style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
		<Form ref={formRef} onFinish={onFinish} layout='inline'>
			<Form.Item name={"storeName"}>
				<Input style={{ width: 120 }} suffix={<SearchOutlined />} placeholder={"门店名称"} />
			</Form.Item>
			<Form.Item name={"contactsOrMobile"}>
				<Input style={{ width: 120 }} suffix={<SearchOutlined />} placeholder={"联系方式"} />
			</Form.Item>
			<Form.Item name={"area"}>
				<TheArea ref={areaRef} setAreaData={setAreaData} />
			</Form.Item>
			<Form.Item name={"isProprietary"}>
				<Select placeholder="门店类型"
					style={{ width: 100 }}
					options={[
						{
							value: 'Y',
							label: '自营'
						},
						{
							value: 'N',
							label: '非自营'
						}
					]} />
			</Form.Item>
			<Form.Item name={"time"} label="入驻时间">
				<RangePicker style={{ width: 240 }} />
			</Form.Item>
			<Form.Item>
				<Space>
					<Button type='primary' htmlType='submit'>搜索</Button>
					<Button onClick={reset}>重置</Button>
				</Space>
			</Form.Item>
		</Form>
	</div>
}

class Examine extends React.Component {
	state = {
		columnsS: [
			{
				title: '门店名称',
				dataIndex: 'storeName',
				key: 'storeName'
			},
			{
				title: '门店图片',
				dataIndex: 'storeShowFile',
				key: 'storeShowFile',
				render: (text, record) => {
					return <TheImage height={80} width={80} src={record.storeShowFile} />
				}
			},
			{
				title: '联系人',
				dataIndex: 'storeContacts',
				key: 'storeContacts'
			},
			{
				title: '联系方式',
				dataIndex: 'userMobile',
				key: 'userMobile'
			},
			{
				title: '地区',
				render: (text, record) => {
					return `${record.addressProvince} ${record.addressCity} ${record.addressDistrict}`
				}
			},
			{
				title: '详细地址',
				dataIndex: 'addressDetail',
				key: 'addressDetail'
			},
			{
				title: "审核状态",
				render: () => {
					return <span>待审核</span>
				}
			},
			{
				title: "申请时间",
				dataIndex: "createTime",
				key: "createTime",
			},
			{
				title: "门店类型",
				dataIndex: 'isProprietary',
				key: 'isProprietary',
				render: (text, record) => {
					return record.isProprietary === 'Y' ? '自营' : '非自营'
				}
			},
			{
				title: "操作",
				fixed: "right",
				render: (text, render) => {
					return (
						<div>
							<TheButton haspermi={['store:details']} onClick={() => this.props.history.push(`/store/details/${render.storeId}`)}>详情</TheButton>
							<TheButton haspermi={['store:pass']} onClick={() => this.openThroughDialog(render.storeId)}>通过</TheButton>
							<TheButton haspermi={['store:rejected']} onClick={() => this.setState({visible:true,textArea:'',storeId:render.storeId})}>驳回</TheButton>
						</div>
					);
				},
			},
		],
		dataS: [],
		columnsB: [
			{
				title: '门店名称',
				dataIndex: 'storeName',
				key: 'storeName'
			},
			{
				title: '门店图片',
				dataIndex: 'storeShowFile',
				key: 'storeShowFile',
				render: (text, record) => {
					return <TheImage height={80} width={80} src={record.storeShowFile} />
				}
			},
			{
				title: '联系人',
				dataIndex: 'storeContacts',
				key: 'storeContacts'
			},
			{
				title: '联系方式',
				dataIndex: 'userMobile',
				key: 'userMobile'
			},
			{
				title: '地区',
				render: (text, record) => {
					return `${record.addressProvince} ${record.addressCity} ${record.addressDistrict}`
				}
			},
			{
				title: '详细地址',
				dataIndex: 'addressDetail',
				key: 'addressDetail'
			},
			{
				title: "审核状态",
				render: () => {
					return <span>未通过</span>
				}
			},
			{
				title: "申请时间",
				dataIndex: "createTime",
				key: "createTime",
			},
			{
				title: "门店类型",
				dataIndex: 'isProprietary',
				key: 'isProprietary',
				render: (text, record) => {
					return record.isProprietary === 'Y' ? '自营' : '非自营'
				}
			},
			{
				title: '原因',
				dataIndex: 'refuseReason',
				key: 'refuseReason'
			}
		],
		dataB: [],
		pageDataS: {
			pageNo: 1,
			pageSize: 10,
		},
		totalS: 0,
		pageDataB: {
			pageNo: 1,
			pageSize: 10,
		},
		totalB: 0,
		visible: false,
		approvalStatus: 'S',
		searchValue: {},
		throughVisible: false,
		throughId: '',
		storeId: '',
		textArea: ''
	};
	async componentDidMount() {
		await this.getData()
	}
	getData = async () => {
		const { approvalStatus, searchValue } = this.state
		let res = await apiGetStoreInfoPage({ approvalStatus, ...searchValue, ...this.state[`pageData${approvalStatus}`] })
		if (res.data && res.code === 0) {
			this.setState({
				[`data${approvalStatus}`]: res.data,
				[`pageData${approvalStatus}`]: {
					pageNo: res.pageNo,
					pageSize: res.pageSize
				},
				[`total${approvalStatus}`]: res.totalCount
			})
		}
	}
	tabChange = (key) => {
		this.setState({
			approvalStatus: key
		}, () => {
			this.getData()
		})
	};
	pageChangeS = (pageNo, pageSize) => {
		this.setState({
			pageDataS: {
				pageNo, pageSize
			}
		})
	};
	pageChangeB = (pageNo, pageSize) => {
		this.setState({
			pageDataB: {
				pageNo, pageSize
			}
		})
	};
	getValue = (value) => {
		this.setState({
			searchValue: value
		}, () => {
			this.getData()
		})
	}
	openThroughDialog = id => {
		this.setState({
			throughVisible: true,
			throughId: id
		})
	}
	closeThroughDialog = () => {
		this.setState({
			throughVisible: false,
			throughId: ''
		})
	}
	openRejectedDialog = (storeId) => {
		this.setState({ visible: true, storeId })
	}
	handleCancel = () => {
		this.setState({ visible: false, storeId: '' });
	};
	handleOk = async () => {
		const dismissReason = this.state.textArea
		if (!dismissReason) {
			return React.$message({
				type: 'error',
				content: '请输入驳回原因'
			})
		} else {
			let res = await apiStoreInfoRejected({ storeId: this.state.storeId, dismissReason })
			if (res.code === 0) {
				this.setState({ visible: false }, () => {
					this.getData()
				});
			}
		}
	};
	onFinish = async value => {
		value.storeId = this.state.throughId
		this.setState({ loading: true })
		let res = await apiStoreInfoApprove({ ...value })
		if (res.code === 0) {
			React.$message({
				type: 'info',
				content: '账号添加成功并审核通过'
			})
			this.setState({
				loading: false
			}, () => {
				this.closeThroughDialog()
				this.getData()
			})
		} else {
			this.setState({
				loading: false
			})
		}
	}
	/**
 * @desc 确认自定义密码验证
 * @params Reg {rule} 验证规则
 * @params string {value} 需要验证的字符串
 * @params fun {callback} 回调函数
 * */
	validatePassword = (rule, value, callback) => {
		const password = this.formRef.getFieldsValue(['password']).password;
		if (value !== password) {
			callback('确认两次输入的密码一致')
		}
		callback()
	}
	render() {
		const {
			columnsS,
			columnsB,
			dataS,
			dataB,
			pageDataS,
			pageDataB,
			totalS,
			totalB,
			visible,
			loading,
			throughVisible
		} = this.state;
		return (
			<div className="p-layout-box commodity-examine">
				<div className="p-search-box">
					<SearchHeader getSearchValue={this.getValue} />
				</div>
				<Tabs defaultActiveKey="S" onChange={this.tabChange}>
					<TabPane tab="待审核" key="S">
						<div className="p-layout-content-pagination">
							<TheTable
								scroll={{ x: "max-content", y: '63vh' }}
								columns={columnsS}
								dataSource={dataS}
							/>
							<ThePagination
								pageNo={pageDataS.pageNo}
								pageSize={pageDataS.pageSize}
								total={totalS}
								pageChange={this.pageChangeS}
							/>
						</div>
					</TabPane>
					<TabPane tab="未通过" key="B">
						<div className="p-layout-content-pagination">
							<TheTable
								scroll={{ x: "max-content", y: '63vh' }}
								columns={columnsB}
								dataSource={dataB}
							/>
							<ThePagination
								pageNo={pageDataB.pageNo}
								pageSize={pageDataB.pageSize}
								total={totalB}
								pageChange={this.pageChangeB}
							/>
						</div>
					</TabPane>
				</Tabs>
				<TheDialog
					title="创建门店登录账号"
					width={400}
					visible={throughVisible}
					handleCancel={this.closeThroughDialog}
					footer={null}
				>
					<Form
						ref={(ref) => {
							this.formRef = ref;
						}}
						labelCol={{ span: 6 }}
						onFinish={this.onFinish}
						wrapperCol={{ span: 16 }}
					>
						<Item name="loginName"
							rules={[{ required: true, message: '请输入用户名' },
							{ pattern: /^[0-9a-zA-Z]+$/, message: '只能输入数字与英文字母' }]}
							label={'用户名'}>
							<Input maxLength={16} placeholder={'请输入用户名'} />
						</Item>
						<Item name="password"
							rules={[{ required: true, message: "请输入密码" }, {
								pattern: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*()_.]+)$)^[\w~!@#$%^&*()_.]{8,16}$/,
								message: "密码应为字母，数字，特殊符号(~!@#$%^&*()_.)，两种及以上组合，8-16位字符串，如：abcd@1234"
							}]}
							label="密码">
							<React.FormPassword placeholder={'请输入密码'} />
						</Item>
						<Item name="confirmPassword"
							rules={[{ required: true, message: "请确认密码" }, { validator: this.validatePassword }]}
							label="确认密码">
							<React.FormPassword placeholder={'请确认密码'} />
						</Item>
						<Item name="userName" rules={[{ required: true, message: "请输入姓名" }, { max: 20 }]} label="姓名">
							<React.FormInput placeholder={'请输入姓名'} />
						</Item>
						<Item name="userMobile"
							rules={[{ required: true, message: "请输入手机号" }, { pattern: phoneReg, message: '请输入正确手机号' }]}
							label="手机号">
							<React.FormInput placeholder={'请输入手机号'} />
						</Item>

						<div className="p-text-align">
							<Space size="large">
								<Button key="back" onClick={this.closeThroughDialog}>
									取 消
								</Button>
								<Button type="primary" loading={loading} htmlType="primary">
									通过并发送账号至短信
								</Button>
							</Space>
						</div>
					</Form>
				</TheDialog>
				<TheDialog
					title={
						<div>
							<ExclamationCircleFilled
								style={{ color: "#FAAD14", marginRight: 10 }}
							/>
							输入驳回原因
						</div>
					}
					width={400}
					visible={visible}
					handleCancel={this.handleCancel}
					handleOk={this.handleOk}
				>
					<TextArea
						onChange={(e) => this.setState({
              textArea: e.target.value
            })}
						allowClear
						autoSize={{ minRows: 6, maxRows: 6 }}
						maxLength={20}
						showCount
					/>
				</TheDialog>
			</div>
		);
	}
}

export default Examine;
